package com.bootdo.common.utils;

import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;

public class UploadUtils {
	 public static boolean writeFile(MultipartFile multipartFile, String path, String fileName) throws IOException{
	    	try {
	    		//读
	    		String cfileName = new String(fileName.getBytes(), "UTF-8");
	    		byte[] bytes = multipartFile.getBytes();
	    		FileOutputStream fileOutputStream = new FileOutputStream(new File(path + cfileName));
	    		BufferedOutputStream buffStream = new BufferedOutputStream(fileOutputStream);
	    		//写
	    		buffStream.write(bytes);
	    		//关
	    		buffStream.close();
	    		fileOutputStream.close();
	    		return true;
	    	
	    	} catch (Exception e) {
				e.printStackTrace();
				return false;
			}

	    }
	 
	 public static boolean writeImage(BufferedImage bufImg, String path, String fileName, String typeimg) throws IOException{
	    	try {
	    		// 输出图片
	    		FileOutputStream outImgStream  = new FileOutputStream(path+fileName);
	    		ImageIO.write(bufImg, typeimg, outImgStream);
	    		outImgStream.flush();
	    		outImgStream.close();
	    		return true;
	    	
	    	} catch (Exception e) {
				e.printStackTrace();
				return false;
			}

	    }
	 
		public static void downloadLocal(String fileAllPath, String fileName, HttpServletResponse response){
			try {
			// 读到流中
	        InputStream inStream = new FileInputStream(fileAllPath);// 文件的存放路径
	        // 设置输出的格式
	        response.reset();
	        response.setContentType("bin");
	        response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
	        // 循环取出流中的数据
	        byte[] b = new byte[1024];
	        int len;
	            while ((len = inStream.read(b)) > 0)
	                response.getOutputStream().write(b, 0, len);
	            inStream.close();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	    }
		
		
		
		   //获取文件后缀名
			public static String getSuffixName(String fileName) {
				if (StringUtils.isEmpty(fileName)) {
					return "";
				} else if (fileName.indexOf(fileName) < 0) {
					return "";
				}
				String suffix = fileName.substring(fileName.lastIndexOf("."));
				return suffix;
			}
}
